package com.cyy.friend.filter;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Component
public class JwtFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        final String authHeader = request.getHeader("Authorization");
        if(authHeader != null && authHeader.startsWith("Bear ")){
            String token = authHeader.substring(5);
            Claims claims = jwtUtils.parseJwt(token);
            if(claims !=null){
                if(claims.get("roles").equals("admin")){//管理员
                    request.setAttribute("admin_claims",claims);
                }
                if("user".equals(claims.get("roles"))){//用户
                    request.setAttribute("user_claims",claims);
                }
            }
        }
        return true;
    }
}
